package com.faiz.picturebed.common;

import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ConfigurableApplicationContext applicationContext;

    public SpringUtils() {
    }

    public void setApplicationContext(@NotNull ApplicationContext applicationContext) {
        initApplicationContext(applicationContext);
    }

    private static void initApplicationContext(ApplicationContext applicationContext) {
        SpringUtils.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static <T> T registerBean(String beanName, Class<T> beanClass, Object... args) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);

        for (Object arg : args) {
            beanDefinitionBuilder.addConstructorArgValue(arg);
        }

        BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory();
        beanFactory.registerBeanDefinition(beanName, beanDefinition);
        return getBean(beanName, beanClass);
    }

    public static String getProperty(String key) {
        return applicationContext.getEnvironment().getProperty(key);
    }

    public static Map<String, Object> getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
        return applicationContext.getBeansWithAnnotation(annotationType);
    }

//    public static String getServiceName() {
//        return ((ConsulDiscoveryProperties)getBean(ConsulDiscoveryProperties.class)).getServiceName();
//    }

    public static ConfigurableApplicationContext getApplicationContext() {
        return applicationContext;
    }

}
